import Mock from 'mockjs';

// 设置延迟时间
Mock.setup({
  timeout: '300-600'
});

// 用户相关接口
Mock.mock(/\/api\/user\/login/, 'post', (options) => {
  const { username, password } = JSON.parse(options.body);
  if (username === 'admin' && password === '123456') {
    return {
      code: 200,
      message: '登录成功',
      data: {
        token: 'mock-token-' + Math.random().toString(36).substr(2),
        userInfo: {
          id: 1,
          username: 'admin',
          name: '管理员',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          roles: ['admin']
        }
      }
    };
  } else {
    return {
      code: 401,
      message: '用户名或密码错误'
    };
  }
});

// 商品相关接口
const productList = [];
for (let i = 1; i <= 50; i++) {
  productList.push(Mock.mock({
    id: i,
    name: `商品${i}`,
    'category|1': ['数码', '食品', '服装', '家居'],
    image: `https://picsum.photos/id/${i + 50}/400/400`,
    description: `这是商品${i}的详细描述信息，展示了商品的特点和使用方法。`,
    'price|100-2000': 100,
    'stock|10-100': 10,
    'status|1': ['在售', '已下架'],
    createTime: '@datetime'
  }));
}

Mock.mock(/\/api\/product\/list/, 'get', (options) => {
  const url = new URL('http://mockjs.com' + options.url);
  const page = parseInt(url.searchParams.get('page')) || 1;
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10;
  const name = url.searchParams.get('name') || '';
  const category = url.searchParams.get('category') || '';
  const status = url.searchParams.get('status') || '';

  let list = productList.filter(item => {
    let nameMatch = true;
    let categoryMatch = true;
    let statusMatch = true;

    if (name) nameMatch = item.name.includes(name);
    if (category) categoryMatch = item.category === category;
    if (status) statusMatch = item.status === status;

    return nameMatch && categoryMatch && statusMatch;
  });

  const total = list.length;
  list = list.slice((page - 1) * pageSize, page * pageSize);

  return {
    code: 200,
    message: '获取成功',
    data: {
      list,
      total,
      page,
      pageSize
    }
  };
});

Mock.mock(/\/api\/product\/detail/, 'get', (options) => {
  const url = new URL('http://mockjs.com' + options.url);
  const id = parseInt(url.searchParams.get('id')) || 0;
  const product = productList.find(item => item.id === id);

  if (product) {
    return {
      code: 200,
      message: '获取成功',
      data: product
    };
  } else {
    return {
      code: 404,
      message: '商品不存在'
    };
  }
});

// 订单相关接口
const statusArray = ['待付款', '待发货', '已发货', '已完成', '已取消'];
const orderList = [];
for (let i = 1; i <= 50; i++) {
  const date = new Date();
  date.setDate(date.getDate() - Mock.Random.integer(0, 30));
  const formattedDate = date.toISOString().split('T')[0] + ' ' + 
                      date.toTimeString().split(' ')[0].substring(0, 5);
  const productId = Mock.Random.integer(1, 50);
  
  orderList.push(Mock.mock({
    id: i,
    orderNo: `ORD${new Date().getFullYear()}${('0000' + i).slice(-4)}`,
    userId: '@integer(1, 20)',
    username: `user@integer(1, 20)`,
    productId,
    productName: `商品${productId}`,
    'quantity|1-5': 1,
    'points|100-1000': 100,
    address: '@county(true)@cword(5, 10)号',
    'status|1': statusArray,
    remark: '@csentence',
    createTime: formattedDate
  }));
}

Mock.mock(/\/api\/order\/list/, 'get', (options) => {
  const url = new URL('http://mockjs.com' + options.url);
  const page = parseInt(url.searchParams.get('page')) || 1;
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10;
  const orderNo = url.searchParams.get('orderNo') || '';
  const username = url.searchParams.get('username') || '';
  const status = url.searchParams.get('status') || '';
  const startDate = url.searchParams.get('startDate') || '';
  const endDate = url.searchParams.get('endDate') || '';

  let list = orderList.filter(item => {
    let orderNoMatch = true;
    let usernameMatch = true;
    let statusMatch = true;
    let dateMatch = true;

    if (orderNo) orderNoMatch = item.orderNo.includes(orderNo);
    if (username) usernameMatch = item.username.includes(username);
    if (status) statusMatch = item.status === status;
    if (startDate && endDate) {
      const itemDate = new Date(item.createTime);
      const start = new Date(startDate);
      const end = new Date(endDate);
      dateMatch = itemDate >= start && itemDate <= end;
    }

    return orderNoMatch && usernameMatch && statusMatch && dateMatch;
  });

  const total = list.length;
  list = list.slice((page - 1) * pageSize, page * pageSize);

  return {
    code: 200,
    message: '获取成功',
    data: {
      list,
      total,
      page,
      pageSize
    }
  };
});

// 用户相关接口
const userList = [];
for (let i = 1; i <= 50; i++) {
  const date = new Date();
  date.setMonth(date.getMonth() - Mock.Random.integer(0, 12));
  date.setDate(date.getDate() - Mock.Random.integer(0, 30));
  const formattedDate = date.toISOString().split('T')[0] + ' ' + 
                      date.toTimeString().split(' ')[0].substring(0, 5);
  
  userList.push(Mock.mock({
    id: i,
    username: `user${i}`,
    name: `用户${i}`,
    'phone|1': [/^1[3-9]\d{9}$/],
    email: `user${i}@example.com`,
    avatar: `https://xsgames.co/randomusers/avatar.php?g=pixel&key=${i}`,
    'points|0-10000': 0,
    'status|1': ['正常', '禁用'],
    remark: '@csentence',
    createTime: formattedDate
  }));
}

Mock.mock(/\/api\/user\/list/, 'get', (options) => {
  const url = new URL('http://mockjs.com' + options.url);
  const page = parseInt(url.searchParams.get('page')) || 1;
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10;
  const username = url.searchParams.get('username') || '';
  const name = url.searchParams.get('name') || '';
  const phone = url.searchParams.get('phone') || '';
  const status = url.searchParams.get('status') || '';

  let list = userList.filter(item => {
    let usernameMatch = true;
    let nameMatch = true;
    let phoneMatch = true;
    let statusMatch = true;

    if (username) usernameMatch = item.username.includes(username);
    if (name) nameMatch = item.name.includes(name);
    if (phone) phoneMatch = item.phone.includes(phone);
    if (status) statusMatch = item.status === status;

    return usernameMatch && nameMatch && phoneMatch && statusMatch;
  });

  const total = list.length;
  list = list.slice((page - 1) * pageSize, page * pageSize);

  return {
    code: 200,
    message: '获取成功',
    data: {
      list,
      total,
      page,
      pageSize
    }
  };
});

export default Mock; 